package com.geo.keyword.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.geo.keyword.entity.KeywordAnalysisRequest;
import com.geo.keyword.entity.KeywordAnalysisResponse;
import com.geo.keyword.dto.KeywordCreateRequest;
import com.geo.keyword.dto.KeywordListResponse;
import com.geo.keyword.entity.Keyword;
import com.geo.keyword.service.KeywordService;
import com.geo.keyword.service.KeywordAnalysisService;
import com.geo.common.result.Result;
import com.geo.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 关键词管理API控制器
 * 
 * @author GEO Team
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/api/keywords")
@Validated
public class KeywordController {
    
    private static final Logger log = LoggerFactory.getLogger(KeywordController.class);
    
    @Autowired
    private KeywordService keywordService;
    
    @Autowired
    private KeywordAnalysisService keywordAnalysisService;
    
    /**
     * 创建关键词
     * @param request 创建请求
     * @return 关键词信息
     */
    @PostMapping
    public Result<Keyword> createKeyword(@Valid @RequestBody KeywordCreateRequest request) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            request.setMerchantId(merchantId);
            
            Keyword keyword = keywordService.createKeyword(request, merchantId);
            
            log.info("创建关键词成功: {}", keyword.getKeywordText());
            return Result.success(keyword);
            
        } catch (Exception e) {
            log.error("创建关键词失败", e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 获取关键词列表
     * @param page 页码
     * @param size 页大小
     * @param status 状态筛选
     * @param keyword 关键词筛选
     * @return 关键词列表
     */
    @GetMapping
    public Result<KeywordListResponse> getKeywords(@RequestParam(defaultValue = "1") int page,
                                                  @RequestParam(defaultValue = "10") int size,
                                                  @RequestParam(required = false) String status,
                                                  @RequestParam(required = false) String keyword) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            KeywordListResponse response = keywordService.getKeywordList(merchantId, page, size, status, keyword);
            
            return Result.success(response);
            
        } catch (Exception e) {
            log.error("获取关键词列表失败", e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 获取关键词详情
     * @param keywordId 关键词ID
     * @return 关键词详情
     */
    @GetMapping("/{keywordId}")
    public Result<Keyword> getKeywordDetail(@PathVariable String keywordId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            Keyword keyword = keywordService.getKeywordDetail(keywordId, merchantId);
            
            return Result.success(keyword);
            
        } catch (Exception e) {
            log.error("获取关键词详情失败: {}", keywordId, e);
            return Result.error(ResultCode.KEYWORD_NOT_FOUND, e.getMessage());
        }
    }
    
    /**
     * 更新关键词
     * @param keywordId 关键词ID
     * @param request 更新请求
     * @return 更新结果
     */
    @PutMapping("/{keywordId}")
    public Result<Keyword> updateKeyword(@PathVariable String keywordId,
                                        @Valid @RequestBody KeywordCreateRequest request) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            Keyword keyword = keywordService.updateKeyword(keywordId, request, merchantId);
            
            log.info("更新关键词成功: {}", keyword.getKeywordText());
            return Result.success(keyword);
            
        } catch (Exception e) {
            log.error("更新关键词失败: {}", keywordId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 删除关键词
     * @param keywordId 关键词ID
     * @return 删除结果
     */
    @DeleteMapping("/{keywordId}")
    public Result<String> deleteKeyword(@PathVariable String keywordId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            keywordService.deleteKeyword(keywordId, merchantId);
            
            log.info("删除关键词成功: {}", keywordId);
            return Result.success("删除成功");
            
        } catch (Exception e) {
            log.error("删除关键词失败: {}", keywordId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 分析关键词
     * @param request 分析请求
     * @return 分析结果
     */
    @PostMapping("/analyze")
    public Result<KeywordAnalysisResponse> analyzeKeyword(@Valid @RequestBody KeywordAnalysisRequest request) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            request.setMerchantId(merchantId);
            
            KeywordAnalysisResponse response = keywordAnalysisService.analyzeKeyword(request);
            
            log.info("关键词分析成功: {}", request.getKeywordText());
            return Result.success(response);
            
        } catch (Exception e) {
            log.error("关键词分析失败", e);
            return Result.error(ResultCode.AI_API_ERROR, e.getMessage());
        }
    }
    
    /**
     * 异步分析关键词
     * @param request 分析请求
     * @return 分析任务ID
     */
    @PostMapping("/analyze-async")
    public Result<String> analyzeKeywordAsync(@Valid @RequestBody KeywordAnalysisRequest request) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            request.setMerchantId(merchantId);
            
            CompletableFuture<KeywordAnalysisResponse> future = keywordAnalysisService.analyzeKeywordAsync(request);
            
            // 返回任务ID，实际项目中应该有任务管理机制
            String taskId = "task_" + System.currentTimeMillis();
            
            log.info("关键词异步分析任务已提交: {}", request.getKeywordText());
            return Result.success("分析任务已提交", taskId);
            
        } catch (Exception e) {
            log.error("关键词异步分析失败", e);
            return Result.error(ResultCode.AI_API_ERROR, e.getMessage());
        }
    }
    
    /**
     * 批量分析关键词
     * @param requests 分析请求列表
     * @return 分析结果列表
     */
    @PostMapping("/batch-analyze")
    public Result<List<KeywordAnalysisResponse>> batchAnalyzeKeywords(@Valid @RequestBody List<KeywordAnalysisRequest> requests) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            // 设置商家ID
            requests.forEach(request -> request.setMerchantId(merchantId));
            
            List<KeywordAnalysisResponse> responses = keywordAnalysisService.batchAnalyzeKeywords(requests);
            
            log.info("批量关键词分析完成: {} 个关键词", requests.size());
            return Result.success(responses);
            
        } catch (Exception e) {
            log.error("批量关键词分析失败", e);
            return Result.error(ResultCode.AI_API_ERROR, e.getMessage());
        }
    }
    
    /**
     * 获取关键词扩展建议
     * @param seedKeyword 种子关键词
     * @param industry 行业
     * @return 扩展关键词列表
     */
    @GetMapping("/expand")
    public Result<List<String>> getKeywordExpansions(@RequestParam String seedKeyword,
                                                     @RequestParam(required = false) String industry) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            List<String> expansions = keywordAnalysisService.getKeywordExpansions(seedKeyword, merchantId, industry);
            
            log.info("获取关键词扩展成功: {} -> {} 个扩展", seedKeyword, expansions.size());
            return Result.success(expansions);
            
        } catch (Exception e) {
            log.error("获取关键词扩展失败", e);
            return Result.error(ResultCode.AI_API_ERROR, e.getMessage());
        }
    }
    
    /**
     * 启动关键词监控
     * @param keywordId 关键词ID
     * @return 启动结果
     */
    @PostMapping("/{keywordId}/start-monitoring")
    public Result<String> startMonitoring(@PathVariable String keywordId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            keywordService.startMonitoring(keywordId, merchantId);
            
            log.info("启动关键词监控: {}", keywordId);
            return Result.success("监控已启动");
            
        } catch (Exception e) {
            log.error("启动关键词监控失败: {}", keywordId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 停止关键词监控
     * @param keywordId 关键词ID
     * @return 停止结果
     */
    @PostMapping("/{keywordId}/stop-monitoring")
    public Result<String> stopMonitoring(@PathVariable String keywordId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            keywordService.stopMonitoring(keywordId, merchantId);
            
            log.info("停止关键词监控: {}", keywordId);
            return Result.success("监控已停止");
            
        } catch (Exception e) {
            log.error("停止关键词监控失败: {}", keywordId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 获取关键词监控数据
     * @param keywordId 关键词ID
     * @param days 查询天数
     * @return 监控数据
     */
    @GetMapping("/{keywordId}/monitoring-data")
    public Result<Object> getMonitoringData(@PathVariable String keywordId,
                                           @RequestParam(defaultValue = "7") int days) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            Object monitoringData = keywordService.getMonitoringData(keywordId, merchantId, days);
            
            return Result.success(monitoringData);
            
        } catch (Exception e) {
            log.error("获取关键词监控数据失败: {}", keywordId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
}